package ltd.sshine.networkclient.service.impl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import ltd.sshine.networkclient.service.ProxyService;
import ltd.sshine.networkcommon.constraint.ChannelConstraint;

import java.net.InetSocketAddress;

public class ProxyServiceImpl implements ProxyService {
    @Override
    public void proxy(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest, String localhost, int localPort) {
        InetSocketAddress remoteAddress = new InetSocketAddress(localhost,localPort);
        HttpHeaders headers = fullHttpRequest.headers();
        String channelId = headers.get(ChannelConstraint.CHANNEL_ID);
        ChannelFuture connect = new Bootstrap()
                .group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new HttpClientCodec());
                        channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024 * 1024));

                        channel.pipeline().addLast(new SimpleChannelInboundHandler<>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx0, Object msg) throws Exception {
                                FullHttpResponse copy = ((FullHttpResponse) msg).copy();
                                copy.headers().add(ChannelConstraint.CHANNEL_ID,channelId);
                                ctx.pipeline().lastContext().writeAndFlush(copy);
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx0, Throwable cause) throws Exception {
                                // 处理异常
                                cause.printStackTrace();
                                ctx0.close();
                                ctx.close();
                            }
                        });

                    }
                })
                .connect(remoteAddress);

        connect.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                headers.remove(ChannelConstraint.CHANNEL_ID);
                future.channel().writeAndFlush(fullHttpRequest);
            } else {
                connect.channel().close();
                ctx.channel().close();
            }
        });
    }
}
